var app = app || {};

$(function() {
	"use strict";

	app.editableViewsManager = new Backbone.EditableViewsManager();

	app.TestView = Backbone.EditableView.extend({
		templateId : "#simple-view-template"
	});
	
	/*app.TestParentView = Backbone.View.extend({
		initialize : function() {
			console.log("Template for ParentTestView is " + this.tagName);
		}
	});

	app.TestView = app.TestParentView.extend({
		tagName: "div",

		templateSelector: "#simple-view-template",

		editorTemplate : Handlebars.compile($("#view-editor-template").html()),

		initialize: function() {
			console.log("TestView options are "+this.options);
			_.bindAll(this, "render", "onSave");
			this.template = Handlebars.compile($(this.templateSelector).html());
			app.TestParentView.prototype.initialize.call(this);
		},

		render : function() {
			console.log("Render for "+this.options);
			if(this.options.editMode) {
				this.$el.html(this.editorTemplate());
				$("#view-editor-body").html($(this.templateSelector).html());
				tinymce.init({
    					selector: "#view-editor-body",
					menubar : false,
					plugins: "link image code save",
					toolbar: "save undo redo | styleselect | bold italic | link image | code",
					entity_encoding: "raw",
					save_enablewhendirty: true,
					save_onsavecallback: this.onSave,
					protect: [
						/<%.*%>/g
					],
					inline : true
				});
			}
			else {
				this.$el.html(this.template(this));
			}
			return this;
		},

		onSave : function(arg) {
			$(this.templateSelector).html($("#view-editor-body").html());
			console.log("Saved "+arg);
			app.router.navigate("", true);
		}

	});*/

	app.TestModuleApp = Backbone.View.extend({
		el: $("#test-main-body"),

		template : Handlebars.compile($("#test-main-template").html()),

		initialize: function(options) {
			this.testView = new app.TestView({ 
				editableViewsManager : app.editableViewsManager
			});
			if(options.editMode) {
				app.editableViewsManager.startEditMode();
			}			
			this.render();
		},

		assign : function(view, selector) {
			view.setElement(this.$(selector)).render();
		},

		render : function() {
			this.$el.html(this.template());
			this.assign(this.testView, "#test-view");
			return this;
		}
	});

	app.AppRouter = Backbone.Router.extend({
		routes: {
			"" : "index",
			"index" : "index",
			"edit" : "editIndex"
		},

		index : function() {
			app.editableViewsManager.endEditMode();
			new app.TestModuleApp({ editMode : false});
		},

		editIndex : function() {
			new app.TestModuleApp({ editMode: true});
		}
	});


	app.router = new app.AppRouter();
	Backbone.history.start();
	console.log("backbone.editableViews.js test initialized");
	
});
